<template>
  <div>
    <div
        style="display: flex; justify-content: space-between; align-items: center; width: 100%; border-bottom: 2px solid #cccccc; padding-bottom: 10px">
      <span style="font-size: 17px; color: #333333; font-weight: bold">添加广告</span>
      <i class="el-icon-back" @click="handleBack()"
         style="font-size: 18px; color: deepskyblue; cursor: pointer;">返回</i>
    </div>
    <div style="margin-top: 20px;margin-left: 10px;width: 60%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="广告标题" prop="adHeadline" align="left">
          <el-input v-model="ruleForm.adHeadline"></el-input>
        </el-form-item>
        <el-form-item label="广告视频" prop="video" align="left">
          <div v-if="this.ruleForm.video === ''">
            <el-upload drag
                       class="avatar-uploader el-upload--text"
                       :action="uploadUrl"
                       :multiple="false"
                       :show-file-list="true"
                       :on-success="onFileSuccess"
                       :before-upload="beforeUploadVideo"
                       :on-error="onFileError"
                       :on-progress="uploadProgress"
            >
              <el-progress :percentage="uploadProgressPercent" v-if="uploadProgressPercent > 0"></el-progress>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传mp4/flv/avi文件，且不超过200MB
              </div>
            </el-upload>
          </div>
            <div v-if="this.ruleForm.video !== ''" style="display: flex; align-items: center;">
              <div v-if="this.ruleForm.name !== ''">{{ ruleForm.name }}&nbsp;&nbsp;<span style="color: #545c64;font-size: small"> 文件大小:{{ ruleForm.size }}MB&nbsp;&nbsp; 视频时长:{{ ruleForm.time }}秒</span></div>
              <div style="margin-left: 200px;display: flex">
                <el-upload
                    class="el-upload--text"
                    :action="uploadUrl"
                    :multiple="false"
                    :show-file-list="true"
                    :on-success="onFileSuccess"
                    :before-upload="beforeUploadVideo"
                    :on-error="onFileError"
                    :on-progress="uploadProgress"
                >
                  <el-button type="text" style="color: #409EFF" class="el-upload__text" >更换视频&nbsp;&nbsp;|</el-button>
                  <el-button type="text" style="color: #409EFF" @click="clearPath()">删除</el-button>
                </el-upload>
              </div>
            </div>
        </el-form-item>
        <el-form-item label="推送方式" prop="isType" align="left">
          <el-radio-group v-model="ruleForm.isType">
            <el-radio :label="0" value="0">即时推送</el-radio>
            <el-radio :label="1" value="1">定时推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推送时间" prop="upDateTime" required align="left" v-if="this.ruleForm.isType === 1">
          <el-date-picker
              v-model="ruleForm.upDateTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
          <span style="color: #cccccc; margin-left: 10px;font-size: small">推送时间必须大于当前时间</span>
        </el-form-item>
        <el-form-item label="失效日期" required align="left" prop="downDateTime">
          <el-date-picker
              v-model="ruleForm.downDateTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
          <span style="color: #cccccc; margin-left: 10px;font-size: small">失效日期必须大于当前日期</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="closeAddForm()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
import {serverUrl} from "@/utils/request";
import { addSplitAdvertising } from "@/api/ad/splitAdvertising"
export default {
  name: "AddSplitAdvertising",
  data() {
    return {
      uploadProgressPercent: 0,
      uploadUrl: serverUrl + "/ad/oss/uploadOneFile",
      attrs: {
        accept: '*' //接受文件类型
      },
      file:{
        name: '',
        size: 0,
      },
      ruleForm: {
        adHeadline: '',
        isType: '',
        upDateTime: '',
        downDateTime: '',
        video: '',
        isStatus: 2,
        createDateTime: '',
        name: '',
        size: '',
        time: '',
        splitOrStandby: 0,
      },
      splitOrStandby:0,
      rules: {
        video: [
          { required: true, message: '请上传广告视频', trigger: 'change' }
        ],
        adHeadline: [
          { required: true, message: '请输入广告标题', trigger: 'blur' },
          { min: 3, max: 40, message: '长度在 3 到 40 个字符', trigger: 'blur' }
        ],
        isType: [
          { required: true, message: '请选择推送方式', trigger: 'change' }
        ],
        upDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('推送时间不能为空'));
              }
              const currentTime = new Date();
              currentTime.setHours(currentTime.getHours() + 1); // 可以设置为当前时间之后的时间，这里示例为当前时间1小时后
              if (value < currentTime) {
                callback(new Error('推送时间必须大于当前时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        downDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('失效日期不能为空'));
              }
              const currentTime = new Date();
              currentTime.setDate(currentTime.getDate() + 1);
              if (value < currentTime) {
                callback(new Error('失效日期必须大于当前日期'));
              } else if(value < this.ruleForm.upDateTime) {
                callback(new Error('失效日期必须大于推送时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
      }
    };
  },
  methods: {
    uploadProgress(event) {
      // event 是进度事件，file 是当前上传的文件
      this.uploadPercent = Math.round((event.loaded / event.total) * 100); // 计算进度百分比
      console.log(`上传进度: ${this.uploadPercent}%`);
    },
    submitForm(formName) {
      if (this.ruleForm.isType === 1 && this.ruleForm.upDateTime === ''){
        this.$message({
          message: '请选择推送时间',
          type: 'warning'
        });
        return false;
      }
      if (this.ruleForm.isType ===0 ){
        this.ruleForm.upDateTime = new Date();
      }
      this.ruleForm.createDateTime = new Date();
      if (this.ruleForm.upDateTime <= new Date()){
        this.ruleForm.isStatus = 0;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.video === ''){
            this.$message({
              message: '请先上传视频',
              type: 'warning'
            });
            return false;
          }
          this.ruleForm.splitOrStandby= this.splitOrStandby;
          addSplitAdvertising(this.ruleForm).then(res => {
            if (res.code === 200){
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.resetForm('ruleForm');
              this.$router.go(-1);
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    closeAddForm(){
      this.resetForm('ruleForm');
      this.$router.go(-1);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleBack() {
      this.$router.go(-1);
    },
    clearPath() {
      this.ruleForm.video = '';
      this.ruleForm.name='';
      this.ruleForm.size='';
      this.ruleForm.time='';
      this.uploadProgressPercent =0;
    },
    onFileError(file) {
      this.$message({
        message: '上传失败,请再次尝试',
        type: 'error'
      });
      this.uploadProgressPercent = 0;
      console.log('error', file);
    },
    onFileSuccess(response, file) {
      this.ruleForm.video = response;
      this.ruleForm.name=file.name;
      this.ruleForm.size=(file.size/(1024*1024)).toFixed(2);
      // 创建一个新的视频元素
      const video = document.createElement('video');

      // 创建一个文件URL
      const videoURL = URL.createObjectURL(file.raw);

      // 设置视频元素的源为文件URL
      video.src = videoURL;

      // 添加loadedmetadata事件监听器，以在元数据加载完成后获取时长
      video.addEventListener('loadedmetadata', () => {
        // 获取视频时长（以秒为单位）
        const duration = video.duration;
        this.ruleForm.time=duration.toFixed(2);
      });
      // 开始加载视频元数据
      video.load();
      this.uploadProgressPercent = 100;

    },
    beforeUploadVideo(file) {
      this.uploadProgressPercent = 0;
      // 上传前的钩子函数，可以在这里进行文件类型和大小的校验
      const isVideo = file.type === 'video/mp4';
      if (!isVideo) {
        this.$message.error('只能上传mp4/flv/avi文件格式!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 200;
      if (!isLt5M) {
        this.$message.error('视频大小不能超过 200MB!');
        return false;
      }
      return true;
    },
  },
  mounted() {
    this.splitOrStandby= this.$route.query.id;
  }
};
</script>

<style scoped>

h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
}

.uploader-list > ul > li {
  width: 100%;
  color: red;
  margin-bottom: 0;
}

a {
  color: #42b983;
}

</style>